package common

import (
	"context"
	"fmt"
	"github.com/gogf/gf/g"
	"github.com/gogf/gf/g/os/gtime"
	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
	"os"
	"io"
	"encoding/base64"
	"crypto/sha1"
	"github.com/qiniu/x/bytes.v7"
	"strconv"
)

const (
	BLOCK_BITS = 22 // Indicate that the blocksize is 4M
	BLOCK_SIZE = 1 << BLOCK_BITS
)

func BlockCount(fsize int64) int {

	return int((fsize + (BLOCK_SIZE-1)) >> BLOCK_BITS)
}

func CalSha1(b []byte, r io.Reader) ([]byte, error) {

	h := sha1.New()
	_, err := io.Copy(h, r)
	if err != nil {
		return nil, err
	}
	return h.Sum(b), nil
}

func GetEtag(filename string) (etag string, err error) {

	f, err := os.Open(filename)
	if err != nil {
		return
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		return
	}

	fsize := fi.Size()
	blockCnt := BlockCount(fsize)
	sha1Buf := make([]byte, 0, 21)

	if blockCnt <= 1 { // file size <= 4M
		sha1Buf = append(sha1Buf, 0x16)
		sha1Buf, err = CalSha1(sha1Buf, f)
		if err != nil {
			return
		}
	} else { // file size > 4M
		sha1Buf = append(sha1Buf, 0x96)
		sha1BlockBuf := make([]byte, 0, blockCnt * 20)
		for i := 0; i < blockCnt; i ++ {
			body := io.LimitReader(f, BLOCK_SIZE)
			sha1BlockBuf, err = CalSha1(sha1BlockBuf, body)
			if err != nil {
				return
			}
		}
		sha1Buf, _ = CalSha1(sha1Buf, bytes.NewReader(sha1BlockBuf))
	}
	etag = base64.URLEncoding.EncodeToString(sha1Buf)
	return
}


//上传图片[]byte到七牛云
func UpLoadImageByteToQiniu(img []byte) (string, error) {

	var qiniuConfig map[string]interface{}= g.Config().GetMap("qiniu")
	putPolicy := storage.PutPolicy{
		Scope:qiniuConfig["Scope"].(string),
	}
	mac := qbox.NewMac(qiniuConfig["AccessKey"].(string), qiniuConfig["SecretKey"].(string))
	upToken := putPolicy.UploadToken(mac)

	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuanan
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false

	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{
		Params: map[string]string{
			//"x:name": "github logo",
		},
	}

	data := img
	dataLen := int64(len(data))
	/*QiniuFileName:=strings.Replace(gtime.Datetime(),":","",-1)
	QiniuFileName=strings.Replace(QiniuFileName," ","",-1)*/
	QiniuFileName:=strconv.FormatInt(gtime.Microsecond(),10)+".png"
	err := formUploader.Put(context.Background(), &ret, upToken, QiniuFileName, bytes.NewReader(data), dataLen, &putExtra)
	if err != nil {
		fmt.Println(err)
		return "",err
	}
	fmt.Println(ret.Key, ret.Hash)
	return qiniuConfig["Domain"].(string) + QiniuFileName, nil
}
